//
//  HttpServices.m
//  CheXunWang
//
//  Created by zhu lin on 12/10/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "HttpServices.h"
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"

@interface HttpServices()
- (NSInteger)indexOfSubArrayInGroupedArray:(NSMutableArray *)groupedArray byKey:(NSString *)aKey withValue:(NSString *)subArrayValue;
@end

@implementation HttpServices

+ (HttpServices *)sharedHttpServices
{
	static HttpServices *services;
	if (services == nil) {
		@synchronized(self) {
			services = [[HttpServices alloc] init]; 
		}
	}
	return services;
}

- (id)init
{
	self = [super init];
	if (self != nil) {
		//
		
	}
	return self;
}

#pragma mark -
#pragma mark common URL generate methods
+ (NSURL *)URLWithBaseString:(NSString *)baseString 
				  parameters:(NSDictionary *)parameters
{   
	NSMutableString *urlString =[NSMutableString string];   //The URL starts with the base string
	[urlString appendString:baseString];
	
	NSInteger keyIndex = 0;   
	for (id key in parameters) 
	{   
		//First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an & 
		NSString *value = (NSString *)[parameters valueForKey:key];
		value = [self encodedAndTrimedParam:value];
		if (value) {
			if(keyIndex == 0) 
			{ 
				[urlString appendFormat:@"?%@=%@",key,value];
			}else{   
				[urlString appendFormat:@"&%@=%@",key,value];
			}   
			keyIndex++; 
		}
	}   
	return [NSURL URLWithString:urlString];   
}

+ (NSString *)encodedAndTrimedParam:(NSString *)param
{
	if (param && ![[param stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]) {
		return [self encodeURLParam:param];
	}
	
	return nil;
}

+ (NSString*)encodeURLParam:(NSString *)param
{
	NSString *encodedParam = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
																				 (CFStringRef)param, 
																				 NULL, 
																				 CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),
																				 CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
							  autorelease];
	return encodedParam;
}

#pragma mark -
#pragma mark services
// 1.	品牌查询（下行数据）
/*
 传入参数：brandId(品牌编号)，brandName(品牌名称)
 样例：http://api.chexun.com/muser/downBrandInfo.do?brandId=2&brandName=%E5%A5%A5%E8%BF%AA
 */

+ (ASIHTTPRequest *)getBrandsByBrandID:(NSString *)brandID 
			  andBrandName:(NSString *)brandName 
				  delegate:(id)del 

{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downBrandInfo.do";
	
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (brandID) {
		[parametersDic setObject:brandID forKey:@"brandId"];
	}
	if (brandName) {
		[parametersDic setObject:brandName forKey:@"brandName"];
	}
	
	//
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}
// 3.	车系查询（下行数据）
/*
 传入参数：brandId(品牌编号)，companyId(厂商编号)，seriesId(车系编号)，seriesName(车系名称)
 样例：http://api.chexun.com/muser/downSeriesInfo.do?brandId=2&companyId=1&seriesId=1&seriesName=%E5%A5%A5%E8%BF%AA 
 */
+ (ASIHTTPRequest *)getSeriesInfoByBrandID:(NSString *)brandID 
						   companyID:(NSString *)companyID
							seriesID:(NSString *)seriesID 
						  seriesName:(NSString *)seriesName 
						  priceScope:(NSString *)scope
							delegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downSeriesInfo.do";
	
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (brandID) {
		[parametersDic setObject:brandID forKey:@"brandId"];
	}
	if (companyID) {
		[parametersDic setObject:companyID forKey:@"companyId"];
	}
	if (seriesID) {
		[parametersDic setObject:seriesID forKey:@"seriesId"];
	}
	if (seriesName) {
		[parametersDic setObject:seriesName forKey:@"seriesName"];
	}
	if (scope) {
		[parametersDic setObject:scope forKey:@"priceScope"];
	}
	
	//
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}

// 5.	车型查询（下行数据）
/*
 传入参数：brandId(品牌编号)，companyId(厂商编号)，seriesId(车系编号)，modelId(车型编号)，modelName(车型名称),year(年代款)
 http://api.chexun.com/muser/downModelInfo.do?brandId=2&companyId=1&seriesId=179&modelId=1520&modelName=%E5%A5%A5%E8%BF%AA&year=2007
 */
+ (ASIHTTPRequest *)getModellistBySeriesID:(NSString *)seriesID
								priceScope:(NSString *)scope 
								  delegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downModelInfo.do";
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (seriesID) {
		[parametersDic setObject:seriesID forKey:@"seriesId"];
	}
	if (scope) {
		[parametersDic setObject:scope forKey:@"priceScope"];
	}
	
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}

// 5.	车型查询（下行数据）
/*
 传入参数： modelId(车型编号)
 样例：http://api.chexun.com/muser/downModelDetail.do?modelId=1520
 */
+ (ASIHTTPRequest *)getModelDetailByModelID:(NSString *)modelID delegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downModelDetail.do";
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (modelID) {
		[parametersDic setObject:modelID forKey:@"modelId"];
	}
	
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}

// 6.	车系图片查询（下行数据）
// 7.	经销商信息查询（下行数据）
// 8.	省份列表查询（下行数据）
// 9.	城市列表查询（下行数据）
// 10.	根据价格区间筛选车型报价数据（下行数据）
// 11.	上传车型收藏数据（上行数据）
// 12.	车系车型图片分页查询（下行数据）
/*
 传入参数： seriesId(车系编号)，modelId(车型编号)，pagekeys (查询页数)，pagesize（每页条数）
 样例：http://api.chexun.com/muser/downCarPhotoForPage.do?seriesId=1&modelId=1240&pagekeys=2&pagesize=10
 */
+ (ASIHTTPRequest *)getPhotoListBySeriesId:(NSString *)seriesID 
								   modelId:(NSString *)modelID 
								  pagekeys:(NSString *)pageIndex 
								  pagesize:(NSString *)pageSize 
							   andDelegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downCarPhotoForPage.do";
	
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (seriesID) {
		[parametersDic setObject:seriesID forKey:@"seriesId"];
	}
	if (modelID) {
		[parametersDic setObject:modelID forKey:@"modelId"];
	}
	if (pageIndex) {
		[parametersDic setObject:pageIndex forKey:@"pagekeys"];
	}
	if (pageSize) {
		[parametersDic setObject:pageSize forKey:@"pagesize"];
	}
	
	//
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}

// 获取汽车图片张数
/*
 传入参数： seriesId(车系编号)，modelId(车型编号)
 样例：http://api.chexun.com/muser/downSeriesPhotoCount.do?seriesId=1&modelId=124
 */
+ (ASIHTTPRequest *)getCarPhotoCountBySeriesId:(NSString *)seriesId 
									   modelId:(NSString *)modelId 
								   andDelegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downSeriesPhotoCount.do";
	
	NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
	if (seriesId) {
		[parametersDic setObject:seriesId forKey:@"seriesId"];
	}
	if (modelId) {
		[parametersDic setObject:modelId forKey:@"modelId"];
	}
	
	//
	NSURL *url = [self URLWithBaseString:baseURLstr parameters:parametersDic];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}

// 13.下载导购--降价促销类最新的2条资讯
+ (ASIHTTPRequest *)getLatestNewsWithDelegate:(id)del
{
	NSString *baseURLstr = @"http://api.chexun.com/muser/downCuXiaoNews.do";
	
	NSURL *url = [NSURL URLWithString:baseURLstr];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	[request setDownloadCache:[ASIDownloadCache sharedCache]];
	[request setDelegate:del];
	[request startAsynchronous];
	return request;
}


#pragma mark -
#pragma mark tools
+ (NSMutableArray *)groupArray:(NSArray *)ungroupedArray byKey:(NSString *)akey
{
	NSMutableArray *groupedArray = [NSMutableArray array];
	
	for (id dic in ungroupedArray)
	{
		NSInteger index = [[HttpServices sharedHttpServices] indexOfSubArrayInGroupedArray:groupedArray byKey:akey withValue:(NSString *)[dic valueForKey:akey]];
		NSMutableArray *subArray;
		if (index >= 0) {
			subArray = (NSMutableArray *)[groupedArray objectAtIndex:index];
			[subArray addObject:dic];
			[groupedArray replaceObjectAtIndex:index withObject:subArray];
		} else {
			subArray = [NSMutableArray array];
			[subArray addObject:dic];
			[groupedArray addObject:subArray];
		}
	}
	
	return groupedArray;
}

- (NSInteger)indexOfSubArrayInGroupedArray:(NSMutableArray *)groupedArray 
									 byKey:(NSString *)aKey 
								 withValue:(NSString *)subArrayValue
{
	for (int i = 0; i < [groupedArray count]; i++) {
		NSMutableArray *subArray = [groupedArray objectAtIndex:i];
		
		if ([subArray count] > 0) {
			NSDictionary *aDic = [subArray objectAtIndex:0];
			if ([(NSString *)[aDic valueForKey:aKey] isEqualToString:subArrayValue]) {
				return i;
			}
		}
	}
	
	return -1;
}
@end
